package com.chenyuxin.ilp.security.perm.handler;


import cn.hutool.json.JSONUtil;
import com.chenyuxin.ilp.model.enums.exception.ExceptionEnums;
import com.chenyuxin.ilp.model.pojo.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 捕捉Spring security filter chain 中抛出的未知异常
 */
//@Component
public class PermExceptionHandler extends OncePerRequestFilter {


  @Override
  public void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    try {
      filterChain.doFilter(request, response);
    } catch (AuthenticationException e) {
      Result result = null;
      if(e instanceof PermException){
        PermException permException = (PermException) e;
        result = Result.fail(permException.getCode(), permException.getMessage());
      }else if (e instanceof RefreshException){
        RefreshException refreshException = (RefreshException) e;
        result = Result.fail(refreshException.getCode(),refreshException.getMessage());
      }
      String jsonStr = JSONUtil.toJsonStr(result);
      response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
      PrintWriter writer = response.getWriter();
      writer.print(jsonStr);
      writer.flush();
      writer.close();
    } catch (Exception e) {
      // 处理未知异常
      Result result = Result.fail(ExceptionEnums.SYSTEM_ERROR);
      String jsonStr = JSONUtil.toJsonStr(result);
      response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
      PrintWriter writer = response.getWriter();
      writer.print(jsonStr);
      writer.flush();
      writer.close();
    }
  }
}